/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.metadata.rtcustomization.common;

import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import io.iec.edp.caf.lock.service.api.api.DistributedLock;
import io.iec.edp.caf.lock.service.api.api.DistributedLockFactory;
import lombok.extern.slf4j.Slf4j;

import java.time.Duration;

/**
 * desc 封装caf的分布式锁
 *
 * @author liangff
 * @since 0.1.28-SNAPSHOT
 */
@Slf4j
public class LockUtils {
    /**
     * 加锁
     * @param resource  标识
     * @param second    时长
     * @return          是否成功
     */
    public static boolean tryLock(String resource, int second) {
        // 获取分布式锁，失败则不进行轮询
        DistributedLockFactory lockFactory = SpringBeanUtils.getBean(DistributedLockFactory.class);
        try {
            DistributedLock distributedLock = lockFactory.tryCreateLock(Duration.ofSeconds(0), resource, Duration.ofSeconds(second));
            // 未开启redis，则不需要锁
            if (distributedLock == null) {
                return true;
            }
            return distributedLock.isAcquired();
        } catch (InterruptedException e) {
            log.error("获取分布式锁时线程被打断：" + Thread.currentThread().getName(), e);
            return false;
        }
    }

    /**
     * 加锁，带看门狗，每30s续约，直到线程坏掉
     * @param resource  标识
     * @return          是否成功
     */
    public static boolean tryLock(String resource) {
        // 获取带看门狗的分布式锁，失败则不进行预加载
        DistributedLockFactory lockFactory = SpringBeanUtils.getBean(DistributedLockFactory.class);
        DistributedLock distributedLock = lockFactory.tryCreateLock(resource);
        // 未开启redis，则不需要锁
        if (distributedLock == null) {
            return true;
        }
        return distributedLock.isAcquired();
    }
}
